/* eslint-disable prefer-rest-params */
import './css/phone.less';

// 图片预览
window.wx = window.wx || {};
// 当前地址
let currentUrl = '';
// 图片地址数组
let urls = [];
// 元素
let $ele = null;
// 当前位置
let current = 0;
// 图片预览是否已经加载过
let isLoad = false;
// 预加载图片数量
const loadNum = 2;
// 图片之间的间距
const spacing = 10;
// startx
let _touchStartX = -1;
// endX
let _touchEndX = -1;
// touchStartTime
let _touchStartTime = -1;
// touchEndTime
let _touchEndTime = -1;
const _bodyWidth = $.os.android ? document.body.clientWidth : $('body').width();

const BILI = 2;
// 渲染
const slider = {
    prev() {
        current -= 1;
        if (current < 0) {
            current = 0;
        }
        this.go(current);
    },
    next() {
        current += 1;
        if (current >= urls.length) {
            current = urls.length - 1;
        }
        this.go(current);
    },
    go(curr) {
        const $current = $ele.find('.img-item').eq(curr);
        const src = urls[curr].replace(/\/w\/[0-9]+$/, '');

        const marginLeft = _bodyWidth * curr + spacing * curr;
        $ele.find('.img-list').css({
            '-webkit-transform': `translate3d(${-1 * marginLeft}px, 0px, 0px)`,
            '-webkit-transition-duration': '200ms',
        });
        $ele.find('.status').text(`${curr + 1} / ${urls.length}`);

        // 加载图片
        if (!$current.find('img').length) {
            $current.prop('data-load', 1);
            this.loadImg(src, (width, height) => {
                if (height / width < BILI) {
                    $current.addClass('center');
                }
                $current.append(`<img src="${src}"/>`);
            });
        }

        // 预加载当前图片的前后2张
        for (let i = 1; i <= loadNum; i++) {
            // 后2个
            const nextCurrent = $ele.find('.img-item').eq(curr + i);
            if (curr + i < urls.length && !nextCurrent.prop('data-load')) {
                const _src = urls[curr + i].replace(/\/w\/[0-9]+$/, '');
                nextCurrent.prop('data-load', 1);
                this.loadImg(_src, (width, height) => {
                    if (height / width < BILI) {
                        nextCurrent.addClass('center');
                    }
                    nextCurrent.append(`<img src="${_src}"/>`);
                });
            }
            // 前2个
            const prevCurrent = $ele.find('.img-item').eq(curr - i);
            if (curr - i >= 0 && !prevCurrent.prop('data-load')) {
                const _src = urls[curr - i].replace(/\/w\/[0-9]+$/, '');
                prevCurrent.prop('data-load', 1);
                this.loadImg(_src, (width, height) => {
                    if (height / width < BILI) {
                        prevCurrent.addClass('center');
                    }
                    prevCurrent.append(`<img src="${_src}"/>`);
                });
            }
        }
    },
    loadImg(src, callback) {
        const $img = new Image();

        $img.src = src;
        if ($img.width || $img.complete) {
            callback($img.width, $img.height);
        } else {
            $img.onload = () => {
                const width = $img.width;
                const height = $img.height;
                callback(width, height);
            };
        }
    },
    render() {
        const urlsList = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];
        const html = urlsList
            .map((url, index) => {
                if (url === currentUrl) {
                    current = index - 1;
                }
                return '<div class="img-item"></div>';
            })
            .join('');

        const imgList = $ele.find('.img-list');
        imgList.css('width', `${(_bodyWidth + spacing) * urls.length}px`);
        imgList.html(html);
        slider.next();
        // 显示图片预览
        $ele.show();
    },
};

// 模板
const TEMPLATE = '<div id="wx-previewImage">'
    + '<div class="wx-pI-layer">'
    + '<p class="status"></p>'
    + '<div class="wx-pI-main phone">'
    + '<div class="img-list"></div>'
    + '</div>'
    + '</div>'
    + '</div>';

// 复写previewImage
export default function (args) {
    currentUrl = args.current;
    urls = args.urls || [currentUrl];

    // 初始化
    if (!isLoad) {
        $('body').append(TEMPLATE);
        isLoad = true;

        $ele = $('#wx-previewImage');

        $ele.on('touchstart', '.img-list', event => {
            event.stopPropagation();
            event.preventDefault();
            _touchStartX = event.pageX || event.targetTouches[0].pageX;
            _touchStartTime = Date.now();
        })
            .on('touchmove', '.img-list', event => {
                event.stopPropagation();
                event.preventDefault();
                _touchEndX = event.pageX || event.targetTouches[0].pageX;

                const marginLeft = _touchStartX - _touchEndX + _bodyWidth * current + spacing * current;
                $ele.find('.img-list').css({
                    '-webkit-transform': `translate3d(${-1 * marginLeft}px, 0px, 0px)`,
                    '-webkit-transition-duration': '0ms',
                });
            })
            .on('touchend', '.img-list', event => {
                event.stopPropagation();
                event.preventDefault();
                _touchEndTime = Date.now();
                _touchEndX = event.pageX || event.changedTouches[0].pageX;

                if (Math.abs(_touchEndX - _touchStartX) >= 60) {
                    if (_touchEndX > _touchStartX) {
                        slider.prev();
                    } else {
                        slider.next();
                    }
                } else if (_touchEndTime - _touchStartTime >= 400) {
                    const marginLeft = _bodyWidth * current + spacing * current;
                    $ele.find('.img-list').css({
                        '-webkit-transform': `translate3d(${-1 * marginLeft}px, 0px, 0px)`,
                        '-webkit-transition-duration': '100ms',
                    });
                } else {
                    $ele.hide();
                }
            });
    }

    // 渲染界面
    slider.render(urls);
}
